﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Configuration;
using Castle.DynamicProxy;
using CNKI.TPI.Web.Base;
using CNKI.TPI.Web.Search.IBLL;
using CNKI.TPI.Web.Search.IDAO;
using CNKI.TPI.Web.Search.Model;
using System.Data;
using CNKI.TPI.Web.Admin.IBLL;

namespace CNKI.TPI.Web.UI.Controllers.Submit
{
    //[MyAuth]
    public class SubmitController : BaseController
    {
        ISubmitService submitService = null;
        INaviService naviService = null;
        ISearchService searchService = null;
        ISubmitAdminService submitAdminService = null;
        public SubmitController(ISubmitService submitService, INaviService naviService, ISearchService searchService, ISubmitAdminService submitAdminService)
        {
            this.naviService = generator.CreateInterfaceProxyWithTarget<INaviService>(naviService, new IInterceptor[] { new LogInterceptor() });
            this.submitService = this.generator.CreateInterfaceProxyWithTarget<ISubmitService>(submitService, new IInterceptor[] { new LogInterceptor() });
            this.searchService = generator.CreateInterfaceProxyWithTarget<ISearchService>(searchService, new IInterceptor[] { new LogInterceptor() });
            this.submitAdminService = this.generator.CreateInterfaceProxyWithTarget<ISubmitAdminService>(submitAdminService, new IInterceptor[] { new LogInterceptor() });
        }

        public ActionResult Index(int flag = 1)
        {
            IList<SYS_CMS_OPTION> dblist = submitService.GetSubmitDBList(flag);
            if (dblist != null && dblist.Count > 0)
            {
                foreach (SYS_CMS_OPTION item in dblist)
                {
                    SYS_CMS_DATABASE obj = naviService.GetDatabase(item.DbCode, 0);
                    if (SessionHelper.HasSubmitRight(obj.SysID))
                    {
                        item.HasSubmitRight = 1;
                    }
                    else
                    {
                        item.HasSubmitRight = 0;
                    }
                }
            }
            return View(dblist);
        }
        /// <summary>
        /// 在线审核列表页
        /// </summary>
        /// <returns></returns>
        public ActionResult ReViewListIndex()
        {
            //数据库列表文献
            ViewBag.DatabaseList = naviService.GetDataBaseList(PermissionOption.None);
            //数据库列表多媒体
            //ViewBag.MediaResource = naviService.GetMediaResourceList();
            return View("ReViewListIndex");
        }
        /// <summary>
        /// 在线审核操作页
        /// </summary>
        /// <returns></returns>
        public ActionResult ReViewIndex(string dbCode, int dbID, string mediatype, string displayName)
        {
            //相似词搜索网址
            ViewBag.smartWordAddress = ConfigHelper.GetAppSettingsValue("smartWordAddress");
            //分类类型
            IList<CLS> categoryTypeList = naviService.GetCategoryType(dbCode, dbID);
            ViewBag.CategoryType = categoryTypeList;
            //分类明细
            if (null != categoryTypeList && categoryTypeList.Count > 0)
            {
                IList<CLS_NODE> categoryList = naviService.GetCategoryList(dbCode, categoryTypeList[0].SysID, dbID);
                ViewBag.CategoryList = categoryList;
            }
            else
            {
                ViewBag.CategoryList = new List<CLS_NODE>();
            }
            //检索字段4，
            IList<SYS_CMS_DATABASE_PUBLISH_FIELD> searchField = searchService.GetSearchFieldList(dbID);
            ViewBag.SearchField = searchField;
            ViewBag.MediaType = mediatype;
            ViewBag.DbID = dbID;
            ViewBag.DbCode = dbCode;
            ViewBag.DisplayName = displayName;

            return View();
        }
        /// <summary>
        /// 在线审核查询
        /// </summary>
        /// <param name="form"></param>
        /// <returns></returns>
        [HttpPost]
        [ValidateInput(false)]
        public ActionResult ReViewSearch(FormCollection form)
        {
            int dbID = 0;
            string dbName = "";
            MediaType mediaType = MediaType.Doc;
            int pageSize = 10;//每页显示记录数
            int pageIndexNow = 1;// 当前页    
            int sumCount = 0;//总条数
            int sumPage = 0;//一共多少页
            int disPgae = 8;  //默认显示页数，当页数大于该数值时，按规定格式显示
            string strOrder = "";
            IList<SearchQuery> searchQuery = new List<SearchQuery>();
            string checkedCatID = Request["beforecheckedCatID"];
            int currentSubid = int.Parse(Request["currentSubid"]);
            int selectedCatTypeID = 0;
            if (Request["beforeselectedCatTypeID"] != null && Request["beforeselectedCatTypeID"] != "")
            {
                selectedCatTypeID = int.Parse(Request["beforeselectedCatTypeID"]);
            }
            dbID = int.Parse(Request["dbID"]);
            dbName = Request["dbName"];
            mediaType = (MediaType)int.Parse(Request["MediaType"]);
            pageIndexNow = int.Parse(Request["pageIndexNow"]);

            string conditionValue = string.IsNullOrEmpty(Request["beforeConditionValue"]) ? "" : Request["beforeConditionValue"];
            string viewstatus = "all";
            if (!string.IsNullOrEmpty(Request["beforeQueryValue"]))
            { 
                viewstatus = Request["beforeQueryValue"].ToString();
                if (viewstatus != "all")
                {
                    searchQuery.Add(new SearchQuery("SYS_FLD_CHECKSTATE", viewstatus));
                }
                else
                {
                    searchQuery.Add(new SearchQuery("SYS_FLD_CHECKSTATE", "(0+1+2)"));
                }
            }
            if (conditionValue != "")
            {
                searchQuery.Add(new SearchQuery(Request["beforeConditionKey"], conditionValue, ConditionType.Like));
            }
            string contype = "";
            string conkey = "";
            for (int i = 1; i <= currentSubid; i++)
            {
                conditionValue = string.IsNullOrEmpty(Request["beforeConditionValue" + i]) ? "" : Request["beforeConditionValue" + i];//值
                contype = string.IsNullOrEmpty(Request["beforeConditionType" + i]) ? "0" : Request["beforeConditionType" + i];//and or
                conkey = string.IsNullOrEmpty(Request["beforeConditionKey" + i]) ? "" : Request["beforeConditionKey" + i];//关键词
                if (conditionValue != "")
                {
                    searchQuery.Add(new SearchQuery(conkey, conditionValue, ConditionType.Like, (SearchMatchType)int.Parse(contype)));

                }
            }


            strOrder = GetSort(dbID);
            //检索
            string selectfield = "";
            IList<SYS_CMS_DATABASE_PUBLISH_FIELD> fields = searchService.GetOverviewFieldList(dbID);
            selectfield = string.Join(",", fields.Select(x => x.FieldName));

            if (!selectfield.Contains("SYS_FLD_CHECKSTATE")) //因为后台系统字段不能发布，所以需要手动加入检索列表
            {
                selectfield += ",SYS_FLD_CHECKSTATE";
            }
            if (!selectfield.Contains("SYS_FLD_ERRORINFO"))
            {
                selectfield += ",SYS_FLD_ERRORINFO";
            }
            DataSet ds = searchService.SingleSearch(dbID, dbName, searchQuery, selectedCatTypeID, checkedCatID, "", strOrder, pageIndexNow, pageSize, selectfield,option:PermissionOption.None,enableCache:false);
            if (ds.Tables.Count > 0)
            {
                ViewBag.SearchResult = ds.Tables[0];
                if (ds.Tables["infos"].Rows.Count > 0)
                {
                    sumCount = int.Parse(ds.Tables["infos"].Rows[0]["count"].ToString());//总条数
                }
                sumPage = sumCount / pageSize; //一共多少页
                if (sumCount % pageSize != 0)
                {
                    sumPage = sumPage + 1;
                }
                ViewBag.TotalPage = sumPage;
                ColumnAliasHelper objhelp = new ColumnAliasHelper();
                ViewBag.PageList = objhelp.GetPageList(pageIndexNow, sumPage, disPgae);
                ViewBag.PageNow = pageIndexNow;//当前页
                ViewBag.PageSize = pageSize;
                ViewBag.ResultCount = sumCount.ToString("N0");
                ViewBag.ResultColumnInfo = ds.Tables["ColumnInfo"];
            }
            ViewBag.DbID = dbID;
            ViewBag.DbName = dbName;
            ViewBag.DisplayName = Request["displayName"];
            ViewBag.MediaType = (int)mediaType; //跳转到详细页区分类型用

            // 不合格因素
            ViewBag.ErrorInfo = submitAdminService.GetErrorInfo();
            return PartialView("ReViewResult");
        }
        /// <summary>
        /// 页面排序
        /// </summary>
        /// <param name="dbID"></param>
        /// <returns></returns>
        private string GetSort(int dbID)
        {
            string strOrder = "";
            string sortstr = "desc";//默认按降序
            IList<SYS_CMS_DATABASE_PUBLISH_FIELD> listSort = searchService.GetSortFieldList(dbID);//排序字段集合
            SYS_CMS_DATABASE obj = searchService.GetDataByID(dbID);
            if (obj != null)
            {
                sortstr = obj.OrderType == 1 ? "asc" : "desc";
            }
            if (listSort != null && listSort.Count > 0) //初始化
            {
                ViewBag.SortField = listSort;
                ViewBag.SortFiledNow = listSort[0].FieldName;//当前排序字段
                ViewBag.SortFiledInit = listSort[0].FieldName;//默认排序字段
                strOrder = listSort[0].FieldName + " " + sortstr;
            }
            else
            {
                ViewBag.SortField = null;
                ViewBag.SortFiledNow = "";//
            }

            ViewBag.SortDescAsc = sortstr;
            ViewBag.SortDescInit = sortstr;//默认排序

            if (Request["sortField"] != null && Request["sortField"].ToString() != "")//如果页面有值就重新赋值
            {
                ViewBag.SortFiledNow = Request["sortField"];
                if (Request["sortDescAsc"] != "")
                {
                    ViewBag.SortDescAsc = Request["sortDescAsc"];
                }
                strOrder = Request["sortField"] + " " + Request["sortDescAsc"];
            }
            return strOrder;
        }
        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="idlist"></param>
        /// <returns></returns>
        public bool DelMetaData(string dbcode, int sysid)
        {
            return submitAdminService.DelMetaData(dbcode, sysid);
        }
        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="idlist"></param>
        /// <returns></returns>
        public bool UpdateMetaData(string dbCode, string status, string errorinfo, string sysid)
        {
            return submitAdminService.UpdateMetaData(dbCode, status, errorinfo, sysid);
        }
        /// <summary>
        /// 是否有审核权限
        /// </summary>
        /// <param name="list"></param>
        /// <returns></returns>
        public bool CheckSubmit(int dbid)
        {
            return SessionHelper.HasCheckRight(dbid);
        }
    }
}
